package com.czk.springcloud.service;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

/**
 * @Author:ChenZhangKun
 * @Date: 2020/12/18 15:49
 */
@Service
@Slf4j
public class PaymentService {
    /**
     * 访问ok的方法
     *
     * @param id
     * @return
     */
    public String paymentInfo_Ok(Integer id) {
        return "线程池" + Thread.currentThread().getName() + " paymentInfo_OK " + id + "\t" + "O(∩_∩)O哈哈~";
    }

    /**
     * 访问失败的方法
     * HystrixCommand 定义兜底方法，出问题时调用其定义的方法
     *
     * @param id
     * @return
     * @throws InterruptedException
     */
/*    @HystrixCommand(fallbackMethod = "paymentInfo_FailHandler", commandProperties = {
            // "execution.isolation.thread.timeoutInMileSeconds这个线程超时2秒钟事则会调用兜底方法
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "2000")
    })*/
    public String paymentInfo_Fail(Integer id) throws InterruptedException {
        // 超时异常，此时也会服务降级
        // TimeUnit.SECONDS.sleep(3);
        // 运行异常 此时也会服务降级
        int i = 10 / 0;
        return "线程池" + Thread.currentThread().getName() + " paymentInfo_Fail " + id + "\t" + "耗时三秒钟";
    }

    /**
     * paymentInfo_Fail的兜底方法
     *
     * @param id
     * @return
     */
    public String paymentInfo_FailHandler(Integer id) {
        return "线程池" + Thread.currentThread().getName() + " paymentInfo_FailHandler " + id + "\t" + "o(╥﹏╥)o";
    }

    //==============服务熔断

    @HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback",commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"), // 是否开启断路器
            // 在时间窗口期10s中以内时，10次请求超过6次失败就会跳闸（服务熔断）此时传入正常的参数也不能访问，需要慢慢的恢复调用链路
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"), // 请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"), // 时间窗口期
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"), // 失败率达到多少后跳闸
    })
    public String paymentCircuitBreaker( Integer id) {
        requestTime++;
        if (id < 0) {
            throw new RuntimeException("id不能为负数");
        }
        String serialNumber = IdUtil.simpleUUID();
        return Thread.currentThread().getName() + "\t" + "调用成功，流水号" + serialNumber;
    }
    double requestTime=0;
    double i=0;
    public String paymentCircuitBreaker_fallback( Integer id) {
        i++;
        log.info("进入服务熔断方法"+i+"次,总请求 "+requestTime+" 百分率为"+i/requestTime);
        return "id不能为负数，请稍后再试  id" + id;
    }
}
